#include <algorithm>
#include "MainGraphic.h"
#include "../utils.hpp"

MainGraphic::MainGraphic()
    : _app(sf::VideoMode(800, 600), "Magic Red Cap"), _spritePool(10), _sprites(), _act(), _images(), _target(NULL)
{
    _app.SetFramerateLimit(60);
}

void MainGraphic::Display()
{
    std::list<sf::Sprite*>::iterator it;
    vector newPos, oldPos;

    _app.Clear(sf::Color(50, 100, 200));
    for (it = _sprites.begin(); it != _sprites.end(); ++it)
    {
        newPos.set((*it)->GetPosition().x, (*it)->GetPosition().y);
        oldPos = newPos;
        if (_target->x > _app.GetWidth() / 2)
            newPos.x = newPos.x - (_target->x - _app.GetWidth() / 2);
        if (_target->y > _app.GetHeight() / 2)
            newPos.y = newPos.y - (_target->y - _app.GetHeight() / 2);
        (*it)->SetPosition(newPos.x, newPos.y);
        _app.Draw(*(*it));
        (*it)->SetPosition(oldPos.x, oldPos.y);
    }
    _app.Display();
}

action & MainGraphic::GetInput()
{
    sf::Input const & input = _app.GetInput();
    sf::Event event;

    _act.resetBool();
    _app.GetEvent(event);
    if (event.Type == sf::Event::Closed || input.IsKeyDown(sf::Key::Escape))
        Close();
    if (input.IsKeyDown(sf::Key::A))
        _act.left = true;
    else if (input.IsKeyDown(sf::Key::D))
        _act.right = true;
    if (_act.prevSpaceUp && input.IsKeyDown(sf::Key::Space))
    {
        _act.jump = true;
        _act.prevSpaceUp = false;
    }
    else if (!input.IsKeyDown(sf::Key::Space))
        _act.prevSpaceUp = true;
    if (_act.shoot < FLOAT_LIMIT && input.IsKeyDown(sf::Key::K))
        _act.shoot = action::SHOOT_MAX;
    else _act.shoot -= GetElapsedTime();

    return _act;
}

sf::Image  * MainGraphic::requireImage(std::string const & filename)
{
    return _images.requireImage(filename);
}

sf::Sprite * MainGraphic::requireSprite()
{
    _sprites.push_back(_spritePool.getNext());
    return _sprites.back();
}

void MainGraphic::freeImage(std::string const & filename)
{
    _images.disposeOf(filename);
}

void MainGraphic::freeSprite(sf::Sprite * sprite)
{
    _sprites.erase(std::find(_sprites.begin(), _sprites.end(), sprite));
    _spritePool.disposeOf(sprite);
}
